import service from './request.js';

// 用户登录
export const login = async (userid, password) => {
  try {
    const response = await service.post('/account/login', {
      userid,
      password
    });

    // 处理字符串响应
    if (response.data.message.includes('操作成功')) {
      return {
        data: {
          user: { userid },
          token: null
        }
      };
    }

    // 处理JSON响应
    if (!response.data) {
      throw new Error('无效的响应数据');
    }

    if (response.data.code === 200 || response.data.success) {
      return {
        data: {
          user: response.data.user || { userid },
          token: response.data.token
        }
      };
    }

    throw new Error(response.data.message || '登录失败');
    
  } catch (error) {
    console.error('登录失败:', error);
    throw error;
  }
};

// 用户注册
export const register = async (userData) => {
  try {
    const response = await service.post('/account/', userData);
    return response;
  } catch (error) {
    console.error('注册失败:', error);
    throw error;
  }
};

// 修改用户信息
export const updateUser = async (userid, updateData) => {
  try {
    const response = await service.put(`/account/${userid}`, updateData);
    return response;
  } catch (error) {
    console.error('更新用户信息失败:', error);
    throw error;
  }
};

// 获取用户信息
export const getUserInfo = async (userid) => {
  try {
    const response = await service.get(`/account/${userid}`);
    console.log('后端返回的用户信息:', response.data); // 添加调试信息
    // 确保正确处理后端返回的数据结构
    if (response.data && response.data.data) {
      return {
        data: response.data.data
      };
    }
    throw new Error(response.data?.message || '获取用户信息失败');
  } catch (error) {
    console.error('获取用户信息失败:', error);
    throw error;
  }
};